package org.ricks.item;

import java.util.List;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

public final class ItemFactory {
    private static final ConcurrentHashMap<Integer, ItemRegistration> REGISTRY = new ConcurrentHashMap<>();

    public static void register(int typeId, Supplier<ItemBehavior> supplier, ItemMeta meta) {
        REGISTRY.put(typeId, new ItemRegistration(typeId, supplier, meta));
    }

    public static ItemBehavior getBehavior(int typeId) {
        ItemRegistration reg = REGISTRY.get(typeId);
        return reg != null ? reg.getBehaviorSupplier().get() : null;
    }

    public static ItemMeta getMeta(int typeId) {
        ItemRegistration reg = REGISTRY.get(typeId);
        return reg != null ? reg.getMeta() : null;
    }

    // 初始化时加载服务或依赖注入
    static {
        ServiceLoader.load(ItemBehavior.class).forEach(behavior -> {
            ItemMeta meta = behavior.getClass().getAnnotation(ItemMeta.class);
            if (meta != null) {
                register(meta.typeId(), () -> behavior, meta);
            }
        });
    }
}